package site.anxuan.seckill.service.impl;

import lombok.AllArgsConstructor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import site.anxuan.seckill.common.BusinessException;
import site.anxuan.seckill.common.ErrorCode;
import site.anxuan.seckill.dao.ItemStockDao;
import site.anxuan.seckill.service.ItemStockService;

@Service
@AllArgsConstructor
public class ItemStockServiceImpl implements ItemStockService {

    private final Logger logger = LoggerFactory.getLogger(ItemStockServiceImpl.class);

    private final RedisTemplate<String, Object> redisTemplate;

    private final ItemStockDao itemStockDao;

    @Override
    public boolean decreaseStock(int itemId, int amount) {
        int i = itemStockDao.decreaseStock(itemId, amount);
        return i > 0;
    }

    @Override
    public boolean decreaseStockInCache(int itemId, int amount) {
        if (itemId <= 0 || amount <= 0) {
            throw new BusinessException(ErrorCode.PARAMETER_ERROR, "参数不合法！");
        }

        Long result = redisTemplate.opsForValue().decrement("item:stock:" + itemId, amount);
        if (result == null) return false;
        if (result < 0) {
            // 回补库存
            redisTemplate.opsForValue().increment("item:stock:" + itemId, amount);
            logger.info("商品[" + itemId + "]回补"+ amount +"个库存.");
        } else if (result == 0) {
            logger.info("商品[" + itemId + "]已经售罄.");
            redisTemplate.opsForValue().set("item:stock:out:" + itemId, 1);
        }
        return result >= 0;
    }

    @Override
    public boolean increaseStockInCache(int itemId, int amount) {
        redisTemplate.opsForValue().increment("item:stock:" + itemId, amount);
        logger.info("商品[" + itemId + "]回补"+ amount +"个库存.");
        return true;
    }

}
